import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { CompanyModel } from 'app/models/CompanyModel';

import { InterceptorService } from '../../../../share/interceptor.service'

import { CheckboxModule, Message, GrowlModule, InputTextareaModule, LightboxModule } from 'primeng/primeng';
import { FileUploader } from 'ng2-file-upload'   //上传图片
import { MessageService } from 'primeng/components/common/messageservice';

import { TechnologyEntity } from 'app/models/technology-entity';
import { TechnologyModel } from '../../../../models/technologyModel'
import { AddPersonInfoComponent } from 'app/workspace/person-info/add-person-info/add-person-info.component';

declare var AMapUI: any;


@Component({
  selector: 'app-add-company',
  templateUrl: './add-company.component.html',
  styleUrls: ['./add-company.component.css']
})
export class AddCompanyComponent implements OnInit {

  constructor(private router: Router, private http: InterceptorService, private messageService: MessageService) { }

  // deleteIcon : string = '../../../../../assets/images/delete-icon.jpg';
  deleteIcon: string = 'assets/images/delete-icon.jpg';

  companyModelList: CompanyModel[] = []; //初始化公司列表



  collapsedList: boolean[] = []; //初始化控制项目和任务开闭集合

  msgs: Message[] = [];//右上角提示信息

  //private companyName : string;

  //private companyTel : string;

  private companyAddress: string;

  // private address : string;

  //private companyModel : CompanyModel = new CompanyModel();

  provinceOptions: string[];//省集合
  cityOptions: string[];//市
  countyOrDistrictOptions: String[];//县/区

  province: string;//省集合
  city: string;//市
  countyOrDistrict: String;//县/区

  selectedValues: string[] = ['val1', 'val2'];

  pictureUrls: string[] = [];
  pictureUrl: string;
  pictureUrlAll: any[];
  userId: string;
  userCode: string;
  userPwd: string;

  ngOnInit() {
    this.userCode = localStorage.getItem('userCode');
    this.userPwd = localStorage.getItem('userPwd');
    this.userId = localStorage.getItem('userId');
    let companyModel: CompanyModel = new CompanyModel;
    companyModel.userId = this.userId;
    this.companyModelList.push(companyModel);
    this.collapsedList[0] = false;
    //加载时，就查询

    //this.searchCompany();
    this.getProvince();
    this.selectSkillPoint();
    //this.getPictureUrl();
    this.selectCompanysByUserId();
    // this.setPictureUrls();
    //this.addTechnology(null);

  }


  ngAfterViewInit() {
    // if (localStorage.getItem("navIdLast") != null) {
    //   let el1: Element = document.getElementById(localStorage.getItem("navIdLast"));
    //   el1.setAttribute("class", "nav-menu");
    // }
    // let el2: Element = document.getElementById(localStorage.getItem("navIdNow"));
    // alert(el2);
    // el2.setAttribute("class", "nav-menu nav-active");

    // localStorage.setItem("navIdLast", localStorage.getItem("navIdNow"));

  }
  style = {
    "font-sizez": "16px",
    width: "236px",
    height: "34px"
  }
  getPictureUrl() {
    let keyId = "X8M5UrQtfN4SyVxwX1kexe"; //有数据
    // let keyId = "";  
    let proviceUrl = "graduate-web/company/selectPictureById/" + keyId;
    this.http.get(proviceUrl).subscribe(
      res => {
        if (res.json().code == '0000') {
          // 方案1-后端方法
          this.pictureUrls = res.json().data;
          // this.pictureUrlAll = 'http://192.168.22.65/' + this.pictureUrl;  //在后端拼接的
          console.log(this.provinceOptions);
        } else {
          // 方案2-假数据
          let data: any[] = [
            {
              id: "37",
              name: "河北"
            }
          ];
          this.provinceOptions = data;
        }
      }
    );
  }


  private technologyEntityList: TechnologyEntity[];
  private technologyModelList: TechnologyModel[];
  private techid: string;
  private techName: string;
  selectSkillPoint() {
    let proviceUrl = "graduate-web/company/selectSkillPoint";
    this.http.get(proviceUrl).subscribe(
      res => {
        if (res.json().code == '0000') {
          // 方案1-后端方法
          this.technologyModelList = res.json().data;
          // for (var i=0 ; i<this.technologyModelList.length; i++) {
          //   console.log(this.technologyModelList[i].techid);
          //   console.log(this.technologyModelList[i].techName);
          //   this.technologyEntityList = this.technologyModelList[i].skillPointEntityList;
          //   for (var j=0 ;j<this.technologyEntityList.length; j++) {
          //     console.log(this.technologyEntityList[j].id);
          //     console.log(this.technologyEntityList[j].techName);
          //     console.log(this.technologyEntityList[j].pId);
          //   }
          // }

          // this.techid = res.json().data[0].techid;
          // this.techName = res.json().data[0].techName;
          //console.log(this.provinceOptions);
        } else {
          // 方案2-假数据
          let data: any[] = [
            {
              id: "null",
              name: "没有查到数据"
            }
          ];
          this.technologyModelList = data;
        }
      }
    );



  }

  // addCompany(companyModel : CompanyModel) {

  //   this.companyName = companyModel.companyName;

  //   this.companyTel = companyModel.companyTel;

  //   alert(this.companyName);

  //   alert(this.companyTel);

  //   //this.url = "src/mock-data/addstudent.json";

  // }

  selectCompanysByUserId() {
    // let userId : string = "001";

    let proviceUrl = "graduate-web/company/selectCompanysByUserId/" + this.userId;
    this.http.get(proviceUrl).subscribe(
      res => {
        if (res.json().code == '0000') {
          // 方案1-后端方法
          console.log(res.json().data);
          //this.companyModelList[0].entryTime = res.json().data.entryTime;
          console.log(res.json().data.entryTime);
          this.companyModelList = res.json().data;
          // for (var i=0;i<this.companyModelList.length;i++) {
          //   for (var j=0;j<res.json().data.length;j++) {
          //     this.companyModelList[i].entryTime = res.json().data[j].entryTime;
          //     this.companyModelList[i].quitTime = res.json().data[j].quitTime;
          //   }

          // }
        } else {
          // 方案2-假数据
          let data: any[] = [
            {
              userId: this.userId
            }
          ];
          this.companyModelList = data;
        }
      }
    );
  }
  setPictureUrls() {
    if (this.companyModelList.length > 0) {
      for (var i = 0; i < this.companyModelList.length; i++) {
        this.pictureUrls = this.companyModelList[i].pictureUrls;
        for (var j = 0; j < this.pictureUrls.length; j++) {
          this.pictureUrlAll.push({ source: 'this.pictureUrls[j]', thumbnail: 'this.pictureUrls[j]', title: 'Sopranos 1' });
        }
      }
    }


  }

  addPerson: AddPersonInfoComponent;
  // doLogin() {
  //   this.router.navigateByUrl('/workspace/person-info/add-person-info/add-salary'); //可以用相对路径吗

  //   this.addPerson.next();
  // }
  // add(companyModel) {
  //   let url = "graduate-web/company/addCompany/";
  //   let companyAddress = this.province + this.city + this.countyOrDistrict;
  //   companyModel.companyAddress = this.companyAddress;
  //   let body = JSON.stringify(this.companyModel);
  //   this.http.post(url, body).toPromise().then(

  //     res => {
  //       if (res.json().code=="0000") {
  //         this.showDialog("修改成功！" );
  //       }
  //       //this.companyModel = res.json().data;

  //     }

  //   ).catch(
  //     res=>{
  //       this.showDialog("服务异常，请重新尝试");
  //     }
  //   );
  // }
  skillIds: string[] = [];
  addTechnology(skillId) {
    if (skillId == null) {
      this.skillIds = [];
    } else if (this.skillIds.indexOf(skillId) >= 0) {
      for (var i = 0; i < this.skillIds.length; i++) {
        console.log(this.skillIds.indexOf(skillId));
        if (this.skillIds[i] == skillId) {
          this.skillIds.splice(i, 1);
        }
      }
    } else {
      console.log(this.skillIds.indexOf(skillId));
      this.skillIds.push(skillId);
    }
    console.log(this.skillIds);

  }
  //添加公司
  public addCompany(order: string) {
    //alert(order);
    //this.companyModelList.push(new CompanyModel);

    //验证是否填完整
    let lastCompany: CompanyModel = this.companyModelList[this.companyModelList.length - 1];

    



    lastCompany.skillIds = this.skillIds;
    lastCompany.pictureUrls = this.pictureUrls;
    if (lastCompany.companyName == null || lastCompany.entryTime == null) {
      //右上角提示
      // this.messageService.add({
      //   severity: 'info',
      //   summary: '提示',
      //   detail: '填完当前公司后才可添加新公司'
      // });
      this.showDialog('填完当前公司后才可添加新公司');


    } else {


      if (!this.checkOutDate(this.translateTime(new Date(lastCompany.entryTime)), this.translateTime(new Date(lastCompany.quitTime)))) {
        this.showDialog('入职时间不得晚于离职时间！');
        return;
      }
      lastCompany.entryTime = this.translateTime(new Date(lastCompany.entryTime));
      if (lastCompany.quitTime != null) {
        lastCompany.quitTime = this.translateTime(new Date(lastCompany.quitTime));
      }

      let companyModel: CompanyModel = new CompanyModel;
      companyModel.userId = this.userId;
      //保存技术点
      // for (var i = 0; i < this.skillIds.length; i++) {
      //   let companyModel: CompanyModel = new CompanyModel;
      //   companyModel.skillIds[i] = this.skillIds[i];
      // }
      this.companyModelList.push(companyModel);

      this.skillIds = []; //清空
      this.pictureUrls = [];
      //alert(this.companyModelList.length);
      //处理开闭集合
      for (var i = 0; i < this.companyModelList.length - 1; i++) {
        this.collapsedList[i] = true;
      }
      //初始化开闭集合
      //let subCollapsedList: boolean[] = [];
      // this.collapsedList[this.collapsedList.length] = subCollapsedList;
      //this.collapsedList[this.collapsedList.length - 1] = false;

    }

  }

  showViaService() {
    this.messageService.add({ severity: 'success', summary: 'Service Message', detail: 'Via MessageService' });
  }

  /* 删除任务 */
  public deleteCompany(order: string) {
    let lastCompany: CompanyModel = this.companyModelList[this.companyModelList.length - 1];
    let companyId: string = lastCompany.companyId;
    if (companyId == null) {
      if (this.companyModelList.length > 1) {
        this.companyModelList.splice(this.companyModelList.length - 1, 1);

      } else {
        let companyModel: CompanyModel = new CompanyModel;
        companyModel.userId = this.userId;
        this.companyModelList[0] = companyModel;
      }
      // alert("删除公司成功");
      this.showDialog('删除公司成功');
    } else {
      let url: string = "graduate-web/company/deleteCompany/" + companyId + "/" + this.userId + "/" + this.userId;


      this.http.get(url).subscribe(
        res => {
          if (res.json().code == "0000") {
            // localStorage.setItem("navIdNow", "quality-evaluation");
            //this.router.navigateByUrl("/workspace/quality-evaluation");
            // localStorage.setItem("commit_project_status","true");

            if (this.companyModelList.length > 1) {
              this.companyModelList.splice(this.companyModelList.length - 1, 1);
            } else {
              this.companyModelList[0] = new CompanyModel;
            }
            // alert(res.json().message);

            this.showDialog(res.json().message);
          }
          else {
            // alert(res.json().message);
            this.showDialog(res.json().message);
          }
        }
      );
    }




    // let amount: number = this.companyModelList.length;
    // //alert(this.companyModelList.length);
    // //多于一个项目可以删除
    // if (amount > 1) {
    //   let companyBackup: any = this.companyModelList;//备份
    //   this.companyModelList = [];//清空
    //  // alert(this.companyModelList.length);
    //   for (var i = 0; i < amount - 1; i++) {
    //     this.companyModelList[i] = companyBackup[i];
    //     //alert(this.companyModelList.length);



    //   }
    //   //初始化开闭集合
    //   //let subCollapsedList: boolean[] = [];
    //   //this.collapsedList[this.collapsedList.length] = subCollapsedList;
    //   //this.collapsedList[this.collapsedList.length - 1] = false;
    // }
    //alert(this.companyModelList.length);
  }

  //**********************************************提示框Start**************************************88 */
  display: boolean = false;
  messages: "";
  /**
   * 提示框
   */
  showDialog(string) {
    this.messages = string;
    this.display = true;
    let com = this;
    var t = setTimeout(function () { com.display = false }, 1500);
  }
  //**********************************************提示框END**************************************88 */

  //获得省
  getProvince() {
    let proviceUrl = "graduate-web/administrativeRegion/selectProvince";
    this.http.get(proviceUrl).subscribe(
      res => {
        if (res.json().code == '0000') {
          // 方案1-后端方法
          this.provinceOptions = res.json().data;
          console.log(this.provinceOptions);
        } else {
          // 方案2-假数据
          let data: any[] = [
            {
              id: "37",
              name: "河北"
            }
          ];
          this.provinceOptions = data;
        }
      }
    );
  }
  // 改变住址省，触发查询市
  changeProvince(provinceId: string) {
    this.getCity(provinceId);
    console.log(provinceId);
  }

  // 获得市
  getCity(provinceId) {
    // provinceId = "37";
    // 方案1-后端方法
    let cityUrl = "graduate-web/administrativeRegion/selectSubRegionById/" + provinceId;
    console.log(provinceId + "省参数");
    this.http.get(cityUrl).subscribe(
      res => {
        if (res.json().code = "0000") {
          this.cityOptions = res.json().data;
          console.log(this.cityOptions);
        } else {
          // 方案2-假数据
          let data: any[] = [
            {
              id: "38",
              pid: "37",
              name: "石家庄"
            }, {
              id: "124",
              pid: "37",
              name: "保定"
            }, {
              id: "197",
              pid: "37",
              name: "廊坊"
            }, {
              id: "150",
              pid: "37",
              name: "张家口"
            }, {
              id: "84",
              pid: "37",
              name: "邯郸"
            }
          ];
          this.cityOptions = data;
        }
      }
    );
  }

  // 改变住址市，触发改变县区
  changeCity(cityId: string) {
    this.getCountyOrDistrict(cityId);
  }

  // 获得县/区
  getCountyOrDistrict(cityId) {
    // cityId = "38";
    // 方案1-后端方法
    let countyOrDistrictUrl = "graduate-web/administrativeRegion/selectSubRegionById/" + cityId;
    this.http.get(countyOrDistrictUrl).subscribe(
      res => {
        if (res.json().code == "0000") {
          this.countyOrDistrictOptions = res.json().data;
        } else {
          // 方案2-假数据
          let data: any[] = [
            {
              id: "48",
              pid: "38",
              name: "正定县"
            }, {
              id: "203",
              pid: "197",
              name: "大城县"
            }, {
              id: "55",
              pid: "38",
              name: "平山县"
            }, {
              id: "199",
              pid: "197",
              name: "广阳区"
            }, {
              id: "198",
              pid: "197",
              name: "安次区"
            }, {
              id: "43",
              pid: "38",
              name: "裕华区"
            }, {
              id: "39",
              pid: "38",
              name: "长安区"
            }
          ];
          this.countyOrDistrictOptions = data;
        }
      }
    );
  }
  ch = {
    /** 每周第一天，0代表周日 */
    firstDayOfWeek: 0,
    /** 每周天数正常样式 */
    dayNames: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
    /** 每周天数短样式（位置较小时显示） */
    dayNamesShort: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
    /** 每周天数最小样式 */
    dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
    /** 每月月份正常样式 */
    monthNames: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
    /** 每月月份短样式 */
    monthNamesShort: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
  };

  public uploader: FileUploader = new FileUploader({
    // url:"http://localhost:8080/singlePoject/importTest",//要写全路径
    url: this.http.getServerUrl("graduate-web/company/importPicture"),
    method: "POST",
    // allowedFileType:["xls","xlxs"]
  });

  filename = "";//页面显示的文件名
  displayFile: boolean = false;
  //打开导入框
  import(info: any) {
    this.filename = "";
    this.displayFile = true;
    // 打开导入框时清除之前选择的文件记录
    let e: any = document.getElementById('filePath');
    e.value = "";
    this.uploader.clearQueue();
  }

  /**
  * 显示选择文件的框
  */
  show(el: HTMLElement) {
    el.click();
  }

  //选择文件后触发的事件
  selectedFileOnChanged(event: any) {
    this.filename = event.target.value;
  }

  //上传触发事件
  upload() {
    if (this.filename == "") {
      this.showDialog("没有选择文件，请选择文件");
      return;
    }
    let extName = this.filename.substring(this.filename.lastIndexOf('.') + 1);
    if (extName == "jpg" || extName == "bmp" || extName == "gif" || extName == "png") {
      this.uploadFile();
      this.displayFile = false;
    } else {
      this.showDialog("文件类型不正确，请选择正确的Excel文件（.xls|.xlsx）");
    }
  }

  //文件上传执行事件
  uploadFile() {
    let obj = this;
    this.uploader.queue[this.uploader.queue.length - 1].upload();

    this.uploader.queue[this.uploader.queue.length - 1].onSuccess = function (response, status, headers) {
      if (status == 200) {
        let tempRes = JSON.parse(response);
        if (tempRes.code == "0000") {
          obj.pictureUrl = tempRes.data;

          obj.pictureUrls.push(obj.pictureUrl);
          obj.showDialog(tempRes.message);
        } else if (tempRes.code == "1111") {
          obj.showDialog(tempRes.message);
          document.getElementById('btnErrorDataShow').setAttribute('style', 'display:visible');
        } else {
          obj.showDialog("文件数据存在无效值，请检查数据格式");
        }
        ///obj.getData();
      }
      else {
        obj.showDialog("与服务连接异常，请重试！");
      }
    };
  }

  /**
     * 时间转化
     * @param date 日期
     */
  translateTime(date) {
    var seperator1 = '-';
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = '0' + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = '0' + strDate;
    }
    return year + seperator1 + month + seperator1 + strDate + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
    // return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds(); 
  }
  /**
   * 检查两日期的有效性（后日期不得早于前日期） 郑晓东 2018年2月21日
   */
  checkOutDate(inDate: string, outDate: string) {
    if (outDate >= inDate) {
      return true;
    }
    return false;
  }

  /* 提交所有项目 */
  public saveCompany() {
    console.log("this.assignmentList--")
    console.log(this.companyModelList);
    // if (this.companyModelList.length ==1) {
    //   //保存技术点
    //   for (var i = 0; i < this.skillIds.length; i++) {
    //     let companyModel: CompanyModel = new CompanyModel;

    //     let id : string ;
    //     id = this.skillIds[i];
    //     companyModel.skillIds.push(id);
    //     //companyModel.skillIds[i+1] = this.skillIds[i+1];

    //     // this.companyModelList[1].skillIds[i] = this.skillIds[i];
    //   }
    // }
    let lastCompany: CompanyModel = this.companyModelList[this.companyModelList.length - 1];


    lastCompany.userId = this.userId;
    lastCompany.skillIds = this.skillIds;
    lastCompany.pictureUrls = this.pictureUrls;

    if (lastCompany.companyName == null || lastCompany.entryTime == null) {
      //右上角提示
      // this.messageService.add({
      //   severity: 'info',
      //   summary: '提示',
      //   detail: '填完当前公司后才可保存公司'
      // });
      this.showDialog('填完当前公司后才可保存公司');
      console.log("look here");

    } else {

      if (!this.checkOutDate(this.translateTime(new Date(lastCompany.entryTime)), this.translateTime(new Date(lastCompany.quitTime)))) {
        this.showDialog('入职时间不得晚于离职时间！');
        return;
      }
      lastCompany.entryTime = this.translateTime(new Date(lastCompany.entryTime));
      if (lastCompany.quitTime != null) {
        lastCompany.quitTime = this.translateTime(new Date(lastCompany.quitTime));
      }

      for (var i = 0; i < this.companyModelList.length; i++) {
        let companyModel: CompanyModel = this.companyModelList[i];
        companyModel.entryTime = this.translateTime(new Date(companyModel.entryTime));
        if (companyModel.quitTime != null) {
          companyModel.quitTime = this.translateTime(new Date(companyModel.quitTime));
        }
      }
      let url: string = "graduate-web/company/addCompany";
      let body = JSON.stringify(this.companyModelList);

      // for ( var i =0; i<this.skillIds.length; i++) {
      //   let companyModel : CompanyModel = new CompanyModel;
      //   companyModel.skillIds[i] = this.skillIds[i];
      // }

      console.log("assignmentList--" + body);
      this.http.post(url, body).subscribe(
        res => {
          if (res.json().code == "0000") {
            // localStorage.setItem("navIdNow", "quality-evaluation");
            //this.router.navigateByUrl("/workspace/quality-evaluation");
            // localStorage.setItem("commit_project_status","true");
            // alert(res.json().message);
            this.selectCompanysByUserId();
            this.showDialog(res.json().message);
          }
          else {
            // alert(res.json().message);
            this.showDialog(res.json().message);
          }
        }
      );
    }
  }




  /**************************************************公司地址****************************** */

  static indexMap: any;
  // regionAddress: string = ""
  change(i: any,event:any) {
    console.log(event);
    console.log(i)
    let content = this.companyModelList[i].companyAddress;
    let companyMap =this.companyModelList;
   
    console.log(content);
    AddCompanyComponent.indexMap = i;
    AMapUI.loadUI(['misc/PoiPicker'], function (PoiPicker) {

      var poiPicker = new PoiPicker({
        input: 'pickerInput_'+i,

      });

      console.log(poiPicker);
      poiPicker.on('poiPicked', function (poiResult) {

     
        var source = poiResult.source,
          poi = poiResult.item,
          info = {
            // source: source,
            id: poi.id,
            name: poi.name,
            location: poi.location.toString(),
            address: poi.address
          };


        companyMap[AddCompanyComponent.indexMap].poiId=info.id; 
        companyMap[AddCompanyComponent.indexMap].regionAddress = info.name;
        companyMap[AddCompanyComponent.indexMap].companyAddress = info.name;
        //切割字符串
        console.log(info.location);
        let content=info.location.trim().split(",");
        
        companyMap[AddCompanyComponent.indexMap].lng = content[0].trim();
        companyMap[AddCompanyComponent.indexMap].lat = content[1].trim();
        

        // clearInterval(poiPicker);
        // clearInterval(AMapUI);
        // AMapUI.loadUI=null;
      });
    });


  }



}

